package database;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;



public class PasswdDatabaseManager {
	private static PasswdDatabaseManager thisInstance;
	private static Properties passwd;
	
	private PasswdDatabaseManager() throws FileNotFoundException, Exception{
		passwd = getPasswdFormFile();
	}
	
	public void setPasswd(String login, String email) {
		passwd.setProperty(login, email);
	}
	
	public void remove(String login) {
		passwd.remove(login);
	}
	
	public static Properties getPasswd() {
		passwd = null;
		try {
			passwd = getPasswdFormFile();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return passwd;
	}
	
	public void save() throws IOException, Exception {
		final String DEFAULT = "This file stores the login and e-mail of the users for easy access";
		PrepareFiles.prepareFile(getPath(), DEFAULT);
		FileOutputStream out = new FileOutputStream(new File(getPath()));
		passwd.storeToXML(out, DEFAULT);
		out.close();
	}
	
	public static PasswdDatabaseManager getInstance() throws FileNotFoundException, Exception {
		if(thisInstance == null) {
			thisInstance = new PasswdDatabaseManager();
		}
		return thisInstance;
	}
	
	private static Properties getPasswdFormFile() throws FileNotFoundException, Exception {
		Properties passwd = new Properties();
		PrepareFiles
				.prepareFile(getPath(),
						"This file stores the login and e-mail of the users for easy access");
		FileInputStream in = new FileInputStream(new File(getPath()));
		passwd.loadFromXML(in);
		in.close();
		return passwd;
	}
	
	private static String getPath() throws Exception {
		return "Database/passwd.xml";
	}
	
	public static void main(String[] args) throws FileNotFoundException, Exception {
		PasswdDatabaseManager sp = PasswdDatabaseManager.getInstance();
		sp.setPasswd("sheldon", "sheldon@lcc2");
		sp.save();
	}
}